package com.mnb.base.controller;

import com.mnb.base.entity.SysMenu;
import com.mnb.base.entity.SysRole;
import com.mnb.base.entity.SysUser;
import com.mnb.base.service.SysMenuService;
import com.mnb.base.service.impl.SysMenuServiceImpl;
import com.mnb.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (sys_menu)表控制层
 *
 * @author xxxxx
 */
@RestController
@RequestMapping("/system/menu")
public class SysMenuController {
    /**
     * 服务对象
     */
    @Resource
    private SysMenuService sysMenuService;

    @Autowired
    private HttpSession session;

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public R treeselect(SysMenu menu) {
        List<SysMenu> menus = sysMenuService.selectMenuList(menu);
        return R.ok(menus);
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect")
    public R roleMenuTreeselect(Long roleId) {
        Map<String, Object> ajax = new HashMap<String, Object>();
        List<SysMenu> menus = sysMenuService.selectMenuList(new SysMenu());
        ajax.put("checkedKeys", sysMenuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", menus);
        return R.ok(ajax);
    }

    @GetMapping("/list")
    public R list(SysMenu menu) {
        List<SysMenu> menus = sysMenuService.selectMenuList(menu);
        return R.ok(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{menuId}")
    public R getInfo(@PathVariable Long menuId)
    {
        return R.ok(sysMenuService.selectMenuById(menuId));
    }

    @RequestMapping("/insert")
    public R insert(@RequestBody SysMenu sysMenu) {
        sysMenu.setCreateBy(getUserName());
        sysMenu.setCreateTime(new Date());
        return sysMenuService.insert(sysMenu);
    }

    @RequestMapping("/udpate")
    public R udpate(@RequestBody SysMenu sysMenu) {
        return sysMenuService.udpate(sysMenu);
    }

    @RequestMapping("/delete")
    public R delete(Long menuId) {
        return sysMenuService.deleteByMenuId(menuId);
    }

    public String getUserName()
    {
        SysUser user = (SysUser) session.getAttribute("user");
        if(user == null){
            throw new RuntimeException("用户未登录");
        }
        return user.getUserName();
    }
}
